var util = require('../../libs/util.js');
//获取应用实例
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    VerticalNavTop: 0,
    searchShowed: false,
    searchVal: "",
    searchShowed2: false,
    searchVal2: "",
    tagList: [],
    nonTagList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    that.setData({
      tag:e.tag
    })
    this.loadData();
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  search: function () {
    this.loadData();
  },
  showSearch: function () {
    this.setData({
      searchShowed: true
    });
  },
  hideSearch: function () {
    this.setData({
      searchVal: "",
      searchShowed: false
    });
    this.searchTag();
  },
  clearSearch: function () {
    this.setData({
      searchVal: ""
    });
    this.searchTag();
  },
  searchTyping: function (e) {
    this.setData({
      searchVal: e.detail.value
    });
    this.searchTag();
  },
  showSearch2: function () {
    this.setData({
      searchShowed2: true
    });
  },
  hideSearch2: function () {
    this.setData({
      searchVal2: "",
      searchShowed2: false
    });
    this.searchNonTag();
  },
  clearSearch2: function () {
    this.setData({
      searchVal2: ""
    });
    this.searchNonTag();
  },
  searchTyping2: function (e) {
    this.setData({
      searchVal2: e.detail.value
    });
    this.searchNonTag();
  },
  loadData: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    util.getData("/atapi/vehicle/vehicle/fleetTagVehicle", {
      'CO_ID': app.globalData.CO_ID,
      'tag': that.data.tag,
      'searchVal': that.data.searchVal
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        //var count = res.data.data[1][0].COUNT || 0;
        //var pageNumber = Math.ceil(count / that.data.pageSize);
        that.setData({
          tagList: res.data.data[0],
          nonTagList: res.data.data[1],
          tagListAll: res.data.data[0],
          nonTagListAll: res.data.data[1]
          //count: count,
          //pageNumber: pageNumber,
          //page: that.data.page == 0 ? 1 : that.data.page
        });
        //that.setPageStatus();
      } else {
        that.setData({
          //page: 0,
          tagList: [],
          nonTagList:[]
        });
      }
      that.setNumber()
      wx.hideLoading();
    });
  },
  searchTag: function () {
    var that = this;
    var tagListAll = that.data.tagListAll;
    var tagList = [];
    var searchVal = that.data.searchVal;
    if (searchVal == '') {
      tagList = tagListAll;
    } else {
      for (var i = 0; i < tagListAll.length; i++) {
        if (String(tagListAll[i].plate).indexOf(searchVal) > -1 || String(tagListAll[i].name).indexOf(searchVal) > -1) {
          tagList.push(tagListAll[i])
        }
      }
    }
    that.setData({
      tagList: tagList
    })
  },
  searchNonTag: function () {
    var that = this;
    var nonTagListAll = that.data.nonTagListAll;
    var nonTagList = [];
    var searchVal = that.data.searchVal2;
    if (searchVal == ''){
      nonTagList = nonTagListAll;
    } else {
      for (var i = 0; i < nonTagListAll.length; i++) {
        if (String(nonTagListAll[i].plate).indexOf(searchVal) > -1 || String(nonTagListAll[i].name).indexOf(searchVal) > -1) {
          nonTagList.push(nonTagListAll[i])
        }
      }
    }
    that.setData({
      nonTagList: nonTagList
    })
  },
  setNumber: function () {
    var that = this;
    that.setData({
      tagNumber: that.data.tagList.length,
      nonTagNumber: that.data.nonTagList.length
     })
  },
  addToTag: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var tagList = that.data.tagList;
    var nonTagList = that.data.nonTagList;
    var newTag = '';
    for (var i = 0; i < nonTagList.length;i++){
      if (nonTagList[i].ID == id){
        if (nonTagList[i].tags){
          newTag = nonTagList[i].tags + ',' + that.data.tag;
        }else{
          newTag = that.data.tag;
        }
        nonTagList[i].tags = newTag;
        tagList.unshift(nonTagList[i]);
        break;
      }
    }
    util.postData("/atapi/vehicle/vehicle/saveVehicleTag", {
      'id': id,
      'tags': newTag
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var _nonTagList = [];
        for (var i = 0; i < nonTagList.length; i++) {
          if (nonTagList[i].ID != id) {
            _nonTagList.push(nonTagList[i])
          }
        }
        that.setData({
          nonTagList: _nonTagList,
          tagList: tagList
        });
        that.setNumber()
        wx.showToast({
          title: "添加成功",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              //that.loadData();
            }, 3000);
          }
        });
      } else {
        wx.showToast({
          title: "添加失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  deleteFromTag: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var tagList = that.data.tagList;
    var nonTagList = that.data.nonTagList;
    var newTag = '';
    for (var i = 0; i < tagList.length; i++) {
      if (tagList[i].ID == id) {
        console.log(tagList[i].tags)
        newTag = util.arrayDeleteItem(tagList[i].tags.split(','), that.data.tag);
        console.log(newTag)
        tagList[i].tags = newTag.join(','); 
        nonTagList.unshift(tagList[i]);
        break;
      }
    }
    console.log(newTag)
    wx.showModal({
      title: '温馨提示',
      content: '确定删除吗？',
      success(res) {
        if (res.confirm) {
          util.postData("/atapi/vehicle/vehicle/saveVehicleTag", {
            'id': id,
            'tags': newTag.join(',')
          }, function (res, error) {
            console.log(res); console.log(error)
            if (res.data.success) {
              var _tagList = [];
              for (var i = 0; i < tagList.length; i++) {
                if (tagList[i].ID != id) {
                  _tagList.push(tagList[i])
                }
              }
              that.setData({
                tagList: _tagList,
                nonTagList: nonTagList
              });
              that.setNumber()
              wx.showToast({
                title: "删除成功",
                icon: "success",
                duration: 3000,
                success: function () {
                  setTimeout(function () {
                    //that.loadData();
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: "删除失败",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        }

      }
    })
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  shopConfig: function (e) {
    wx.redirectTo({
      url: '/pages/enterprise/shop_priceconfig?id=' + e.currentTarget.dataset.id
    })
  },
  newShop: function (e) {
    wx.redirectTo({
      url: '/pages/enterprise/shop_new'
    })
  },
  editShop: function (e) {
    wx.redirectTo({
      url: '/pages/enterprise/shop_edit?id=' + e.currentTarget.dataset.id
    })
  },
  importShop: function (e) {
    wx.redirectTo({
      url: '/pages/enterprise/shop_import'
    })
  },
  openLocation: function (e) {
    var coord = String(e.currentTarget.dataset.coord).split(",");
    wx.openLocation({
      latitude: Number(coord[0]),
      longitude: Number(coord[1]),
      scale: 18
    })
  },
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})